<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>音乐搜索与播放</title>
    <style>
        :root {
            --bg-color: #f4f4f4;
            --primary-color: #007BFF;
            --hover-color: #0056b3;
            --text-color: #333;
            --column-width: 33%;
            --red-1: 255,236,232;
            --orange-1: 255,247,232;
            --blue-1: 232,247,255;
            --font-size: 16px;
            --line-height: 1.5;
        }
        li:hover {
            background-color: rgba(var(--red-1), 0.3);
        }
        .playing {
            background-color: rgba(var(--blue-1), 1);
        }
        body {
            font-family: 'Arial', sans-serif;
            background: var(--bg-color);
            margin: 0;
            padding: 10px;
            padding-bottom: 100px;
        }
        header {
            background-color: #fff;
            padding: 20px 40px;
            text-align: center;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        form {
            margin-top: 20px;
            text-align: center;
        }
        input[type="text"] {
            width: 300px;
            padding: 10px;
            margin-right: 10px;
            border: 2px solid #ccc;
            border-radius: 5px;
        }
        button {
            padding: 15px 20px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: var(--hover-color);
        }
        ul {
            list-style-type: none;
            padding: 0;
            margin: 20px 0;
        }
        li {
            background: var(--blue-1);
            color: var(--text-color);
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            font-size: var(--font-size);
            line-height: var(--line-height);
            cursor: pointer;
        }
        .column {
            width: var(--column-width);
            text-align: center;
        }
        audio {
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 60px;
            background: white;
            box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
        }
        #timeDisplay, #speedControl, #playMode, #volumeControl {
    margin: 0 10px;
}

#volumeControl {
    width: 100px;
}
#audioPlayerBar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 60px;
    background: white;
    padding: 10px;
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
}

#resultsHeader {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
    background-color: #f0f0f0; /* 轻灰色背景 */
    font-weight: bold; /* 加粗字体 */
}

.header-title, .header-artist, .header-album {
    width: 33%; /* 分配相等宽度 */
    text-align: center; /* 居中文本 */
}

li {
    display: flex;
    justify-content: space-between;
    padding: 5px 0;
}

.song-title, .song-artist, .song-album {
    width: 33%; /* 与标题宽度一致 */
    text-align: center; /* 居中文本 */
}


    </style>
</head>
<body>
    <header>
        <h1>搜索音乐</h1>
    </header>
    <form id="searchForm">
        <input type="text" id="searchQuery" placeholder="输入艺术家、歌曲或专辑" required>
        <button type="submit">搜索</button>
    </form>
    <div id="results"></div>

    <div id="audioPlayerBar">
    <audio id="audioPlayer" controls style="display: none;">
        <source id="audioSource" type="audio/mpeg">
        您的浏览器不支持音频元素。
    </audio>
    <button id="prevButton">|<</button>
    <button id="playPauseButton">▶</button>
    <button id="nextButton">>|</button>
        <input type="range" id="progressBar" value="0" min="0" max="100" style="width: 30%;">


    <div id="timeDisplay">00:00 / 00:00</div>
    <select id="speedControl">
        <option value="0.5">0.5x</option>
        <option value="1" selected>1x</option>
        <option value="1.5">1.5x</option>
        <option value="2">2x</option>
    </select>
    <select id="playMode">
        <option value="sequential">顺序</option>
        <option value="loop">循环</option>
        <option value="random">随机</option>
    </select>
    <input type="range" id="volumeControl" min="0" max="100" value="100">
</div>

    <script>
        let currentIndex = 0; // 当前播放歌曲的索引
        let playlist = []; // 播放列表
        let playMode = 'sequential'; // 默认播放模式

        document.getElementById('searchForm').addEventListener('submit', function(event) {
    event.preventDefault();
    const query = document.getElementById('searchQuery').value;
    fetch(`/search?query=${query}`)
        .then(response => response.text())  // 获取响应的文本，即 HTML
        .then(html => {
            document.getElementById('results').innerHTML = html; // 将 HTML 插入到页面的结果部分
            buildPlaylist(); // 构建播放列表并打印
        })
        .catch(error => console.error('Error loading data:', error));
});






document.getElementById('audioPlayer').addEventListener('ended', function() {
    playNext();
});

document.getElementById('playPauseButton').addEventListener('click', function() {
    const player = document.getElementById('audioPlayer');
    const button = document.getElementById('playPauseButton'); // 获取按钮元素

    if (player.paused) {
        player.play();
        button.textContent = '||'; // 当音乐播放时设置按钮为暂停图标
    } else {
        player.pause();
        button.textContent = '▶'; // 当音乐暂停时设置按钮为播放图标
    }
});


document.getElementById('nextButton').addEventListener('click', playNext);
document.getElementById('prevButton').addEventListener('click', playPrev);

document.getElementById('playMode').addEventListener('change', function() {
    playMode = this.value;
});

document.getElementById('speedControl').addEventListener('change', function() {
    document.getElementById('audioPlayer').playbackRate = parseFloat(this.value);
});

document.getElementById('volumeControl').addEventListener('input', function() {
    document.getElementById('audioPlayer').volume = this.value / 100;
});

// 确保在加载结果后更新 playlist 数组
function buildPlaylist() {
    playlist = []; // 重置播放列表
    document.querySelectorAll('li[data-index]').forEach((element, index) => {
        const songDetails = element.textContent.trim().split(' - ');  // 假设歌曲详情按 " - " 分隔
        const link = element.getAttribute('onclick').match(/'([^']+)'/)[1]; // 从onclick属性中提取URL
        const song = {
            link: link,
            title: songDetails[0],  // 假设歌曲名是第一个元素
            singer: songDetails[1], // 假设歌手名是第二个元素
            album: songDetails[2]  // 假设专辑名是第三个元素
        };
        playlist.push(song);
    });
    console.log("Playlist updated with the following songs:", playlist); // 打印构建好的播放列表
}



// 播放指定索引的歌曲
function playSongByIndex(index) {
    if (index < 0 || index >= playlist.length) {
        console.error("Index out of bounds");
        return;
    }
    currentIndex = index; // 更新当前播放索引
    const song = playlist[index];
    playMusic(song.link, song.title, document.querySelector(`li[data-index="${index}"]`));
}

// // 上一首歌
// document.getElementById('prevButton').addEventListener('click', function() {
//     if (currentIndex > 0) {
//         playPrev(currentIndex - 1);
//     } else {
//         // 如果是第一首歌，循环到最后一首歌
//         playPrev(playlist.length - 1);
//     }
// });
//
// // 下一首歌
// document.getElementById('nextButton').addEventListener('click', function() {
//     if (currentIndex < playlist.length - 1) {
//         playNext(currentIndex + 1);
//     } else {
//         // 如果是最后一首歌，循环到第一首歌
//         playNext(0);
//     }
// });

function playMusic(link, title, element) {
    const player = document.getElementById('audioPlayer');
    const source = document.getElementById('audioSource');
    const button = document.getElementById('playPauseButton'); // 获取按钮元素
    button.textContent = '||'; // 当音乐播放时设置按钮为暂停图标
    currentIndex = parseInt(element.getAttribute('data-index'), 10); // 获取索引并转换为数字

    source.src = link;
    player.load();
    player.play();
    document.title = title;
    updatePlayingIndicator(element);
}

function updatePlayingIndicator(currentElement) {
    const currentlyPlaying = document.querySelector('.playing');
    if (currentlyPlaying) {
        currentlyPlaying.classList.remove('playing');
    }
    currentElement.classList.add('playing');
}


function playNext() {
    if (playlist.length === 0) return;  // 如果没有歌曲，直接返回

    console.log("Current index before next:", currentIndex); // 当前索引

    switch (playMode) {
        case 'sequential': // 顺序播放
            currentIndex++;  // 增加索引
            if (currentIndex >= playlist.length) {
                currentIndex = 0;  // 如果索引超出范围，回到起点
            }
            break;
        case 'loop':
            currentIndex = (currentIndex + 1) % playlist.length;  // 循环播放
            break;
        case 'random':
            let nextIndex = currentIndex;
            let attempts = 0;
            do {
                nextIndex = Math.floor(Math.random() * playlist.length);
                attempts++;
            } while (nextIndex === currentIndex && playlist.length > 1 && attempts < 100);
            currentIndex = nextIndex;
            break;
    }

    console.log("Playing next: from index", currentIndex); // 显示即将播放的索引
    playSongByIndex(currentIndex);
}


function playPrev() {
    if (playlist.length === 0) return;
    let prevIndex = currentIndex - 1;

    switch (playMode) {
        case 'sequential':

        case 'loop': // 顺序和循环在后退时行为一致
            if (prevIndex < 0) {
                prevIndex = playlist.length - 1; // 循环到列表最后
            }
            break;
        case 'random':
            let attempts = 0;
            do {
                prevIndex = Math.floor(Math.random() * playlist.length);
                attempts++;
            } while (prevIndex === currentIndex && playlist.length > 1 && attempts < 100);
            break;
    }

    console.log("Playing previous: from index", currentIndex, "to", prevIndex); // 调试输出
    currentIndex = prevIndex; // 更新当前索引
    playSongByIndex(currentIndex);
}


            function updateTime() {
    const player = document.getElementById('audioPlayer');
    const duration = player.duration; // 音频总时长
    const currentTime = player.currentTime; // 当前播放位置
    const formattedDuration = formatTime(duration);
    const formattedCurrentTime = formatTime(currentTime);

    // 更新显示时间的元素
    document.getElementById('timeDisplay').textContent = `${formattedCurrentTime} / ${formattedDuration}`;

    // 更新进度条的值
    const progressBar = document.getElementById('progressBar');
    if (duration > 0) { // 防止除以零
        progressBar.value = (currentTime / duration) * 100;
    }
}

// 监听音频播放的 timeupdate 事件以定时更新时间和进度条
document.getElementById('audioPlayer').addEventListener('timeupdate', updateTime);


// 辅助函数，格式化时间从秒数转换为 MM:SS 格式
function formatTime(time) {
    if (isNaN(time)) {
        return "00:00";
    }
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${pad(minutes)}:${pad(seconds)}`;
}

// 格式化时间显示，确保数字始终是两位数
function pad(number) {
    return number < 10 ? '0' + number : number;
}

// 设置定时更新
document.getElementById('audioPlayer').addEventListener('timeupdate', updateTime);
document.addEventListener('DOMContentLoaded', function() {
    const player = document.getElementById('audioPlayer');
    const progressBar = document.getElementById('progressBar');

    // 当用户调整进度条时，更新音频播放位置
    progressBar.addEventListener('change', function() {
        if (player.duration) {
            player.currentTime = (this.value / 100) * player.duration;
        }
    });
});






    </script>
</body>
</html>
